package com.yazi.mxz.server.controller;


import java.util.List;

import javax.annotation.Resource;

import mo.framework.smh.common.exception.MyException;
import mo.framework.smh.hibernate.OrderType;
import mo.framework.smh.hibernate.PageInfo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.annotation.JsonView;
import com.yazi.mxz.common.entity.beans.Address;
import com.yazi.mxz.common.entity.beans.Member;
import com.yazi.mxz.common.entity.beans.Order;
import com.yazi.mxz.common.entity.beans.Shopping;
import com.yazi.mxz.common.entity.beans.ShoppingCart;
import com.yazi.mxz.common.entity.beans.StoreGoods;
import com.yazi.mxz.common.entity.custom.OperatorType;
import com.yazi.mxz.common.entity.custom.OrderForSearch;
import com.yazi.mxz.common.entity.custom.OrdersFromForm;
import com.yazi.mxz.common.entity.custom.ShoppingCartsForOrder;
import com.yazi.mxz.common.exception.HcdException;
import com.yazi.mxz.common.service.AddressService;
import com.yazi.mxz.common.service.OrderService;
import com.yazi.mxz.common.service.ShoppingCartService;
import com.yazi.mxz.server.request.ListRequest;
import com.yazi.mxz.server.request.UpdateOrderStatusRequest;
import com.yazi.mxz.server.response.OrderAddFormData;
import com.yazi.mxz.server.response.OrderAddFormResponse;
import com.yazi.mxz.server.response.OrderAddResponse;
import com.yazi.mxz.server.response.OrderListResponse;
import com.yazi.mxz.server.response.StatusResponse;
import com.yazi.mxz.server.response.view.BaseView;
import com.yazi.mxz.server.response.view.OrderAddFormDataView;
import com.yazi.mxz.server.response.view.OrderGoodsesAStoreView;

@Controller("orderController")
@RequestMapping("/order")
public class OrderController extends BaseController {
	private static Logger log = LoggerFactory.getLogger(OrderController.class);
	
	@Resource
	ShoppingCartService shoppingCartService;
	@Resource
	AddressService addressService;
	@Resource
	OrderService orderService;
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/add")
	@ResponseBody
	@JsonView(OrderAddFormDataView.class)
	public OrderAddFormResponse add(@RequestBody ShoppingCartsForOrder cartsObj) {
		Member loginMember = getLoginMember();
		log.debug("客户端 -> 获取订单表单数据：memberId={}", loginMember.getMemberId());
		OrderAddFormResponse res = new OrderAddFormResponse();
		try {
			// 购物车商品
			List<ShoppingCart> cartList = shoppingCartService.checkForOrder(loginMember, cartsObj.getShoppingCarts());
			
			// 用户默认收货地址
			Address defAddress = null;
			Address addressForSearch = new Address();
			addressForSearch.setMember(loginMember);
			addressForSearch.setIsDefault(true);
			List<Address> addressList = addressService.search(addressForSearch, new PageInfo(), null);
			if (addressList.size() == 1) {
				defAddress = addressList.get(0);
			}
			
			OrderAddFormData data = new OrderAddFormData();
			data.setShoppingCarts(cartList);
			data.setAddress(defAddress);
			res.setSuccessData(data);
			res.setOk();
		} catch (HcdException e) {
			log.debug("获取订单表单数据失败:{}", e.getMessage());
			res.setCode(e.getCode());
			res.setFailData((List<Shopping>)e.getData());
			res.setFailMessage(e.getMessage());
		} catch (Exception e) {
			log.error("获取订单表单数据异常:", e);
			res.setErrorMessage("操作失败,请联系管理员");
		}

		return res;
	}	
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/addDo")
	@ResponseBody
	@JsonView(BaseView.class)
	public OrderAddResponse addDo(@RequestBody OrdersFromForm ordersObj){
		Member loginMember = getLoginMember();
		Long memberId = loginMember.getMemberId();
		log.debug("客户端 -> 提交订单：memberId={}", memberId);
		OrderAddResponse res = new OrderAddResponse();
		try {
			orderService.add(loginMember, ordersObj);
			res.setOkMessage("提交成功");
		} catch (HcdException e) {
			log.debug("订单提交失败[{}]:{}", e.getCode(), e.getMessage());
			res.setCode(e.getCode());
			res.setFailData((List<StoreGoods>)e.getData());
			res.setFailMessage(e.getMessage());
		} catch (MyException e) {
			log.debug("订单提交失败[{}]:{}", e.getClass().getSimpleName(), e.getMessage());
			res.setFailMessage("操作失败");
		} catch (Exception e) {
			log.error("订单提交异常:", e);
			res.setErrorMessage("操作失败,请联系管理员");
		}
		return res;
	}
	
	@RequestMapping("/list")
	@ResponseBody
	@JsonView(OrderGoodsesAStoreView.class)
	public OrderListResponse list(@RequestBody ListRequest<OrderForSearch> req){
		log.debug("客户端 -> 获取订单列表");
		OrderListResponse res = new OrderListResponse();
		try {
			OrderForSearch orderForSearch = req.getQueryObject();
			orderForSearch.setMember(getLoginMember());
			orderForSearch.setIsMemberDel(false);
			PageInfo pageInfo = req.getPageInfo();
			if (pageInfo.getOrderField().isEmpty()) {
				// 默认按订单时间倒序
				pageInfo.setOrderField("orderTime");
				pageInfo.setOrderType(OrderType.DESC);
			}
			// 订单列表
			List<Order> orderList = orderService.search(orderForSearch, pageInfo, req.getSearchWord());
			res.setSuccessData(orderList);
			res.setOk();
		} catch (Exception e) {
			log.error("获取订单列表异常:", e);
			res.setErrorMessage("操作失败,请联系管理员");
		}
		return res;
	}
	
	@RequestMapping("/statusDo")
	@ResponseBody
	public StatusResponse statusDo(@RequestBody UpdateOrderStatusRequest req){
		log.debug("客户端 -> 更新订单状态");
		StatusResponse res = new StatusResponse();
		try {
			for (String orderCode : req.getOrderCodes()) {
				orderService.updateStatus(getLoginMember(), orderCode, req.getStatus());
			}
			res.setOk();
		} catch (Exception e) {
			log.error("更新订单状态异常:", e);
			res.setErrorMessage("操作失败,请联系管理员");
		}
		return res;
	}
	
	@RequestMapping("/removeDo")
	@ResponseBody
	public StatusResponse removeDo(@RequestBody Order order) {
		log.debug("客户端 -> 删除订单");
		StatusResponse res = new StatusResponse();
		res.setFailMessage("删除失败");
		try {
			if (orderService.delete(getLoginMember(), order.getOrderCode(), OperatorType.MEMBER)) {
				res.setOkMessage("删除成功!");
			}
		} catch (Exception e) {
			log.error("删除订单异常:", e);
			res.setErrorMessage("操作失败,请联系管理员");
		}
		return res;
	}
	
}
